package org.wesc.boot.service.common;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.wesc.boot.service.exception.ServiceErrorCode;
import org.wesc.boot.service.exception.ServiceException;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * 通用服务
 * @author Wesley
 * @date 2021/5/21
 */
@Slf4j
@Service
public class CommonService {

    /**
     * 下载文件
     * @param filename 文件名
     */
    public void downloadFile(String filename, HttpServletResponse response) throws ServiceException {
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            if (StringUtils.isEmpty(filename)) {
                throw new ServiceException(ServiceErrorCode.EMPTY_FILENAME);
            }

            // 获取文件
            File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "static/" + filename);
            if (file.exists()) {
                // 配置文件下载
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                // 下载文件能正常显示中文
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));

                byte[] buffer = new byte[1024];
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } else {
                throw new ServiceException(ServiceErrorCode.NO_FILE_FOUND);
            }
        } catch (Exception e) {
            throw new ServiceException(ServiceErrorCode.DOWNLOAD_FAIL);
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
